'''
python文件 - 有道翻译
'''
import requests
import json
import time
import random
from hashlib import md5

class YdSpider:
    def __init__(self):
        # post_url:F12抓包转到的POST的地址
        self.post_url = 'https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
        self.headers = {
            # headers中检查频率最高的User-Agent、Cookie、Referer
            '''Cookie''': '''OUTFOX_SEARCH_USER_ID=-441685778@103.102.194.226; OUTFOX_SEARCH_USER_ID_NCOO=1311232133.5140777; _ntes_nnid=a6a6cfcf2f13779cd11ad8e2ca44836d,1595664981237; _ga=GA1.2.1866744817.1598613276; JSESSIONID=aaaeIHtcOn2cm55e3gfQx; SESSION_FROM_COOKIE=unknown; ___rl__test__cookies=1625734695963''',
            '''Referer''': '''https://fanyi.youdao.com/''',
            '''User-Agent''': '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36''',
        }
        self.word = input('Input word:')

    def md5s(self, s):
        """md5加密函数"""
        m = md5()
        m.update(s.encode())

        return m.hexdigest()

    def get_ts_salt_sign(self):
        """获取ts salt sign"""
        ts = str(int(time.time() * 1000))
        salt = ts + str(random.randint(0, 9))
        s = "fanyideskweb" + self.word + salt + "Y2FYu%TNSbMCxc3t2u^XT"
        sign = self.md5s(s)

        return ts, salt, sign

    def attack_yd(self):
        """爬虫逻辑函数"""
        # 获取ts salt sign
        ts,salt,sign = self.get_ts_salt_sign()
        data = {
            "i": self.word,
            "from": "AUTO",
            "to": "AUTO",
            "smartresult": "dict",
            "client": "fanyideskweb",
            # sign、salt
            "salt": salt,
            "sign": sign,
            "lts": ts,
            "bv": "cda1e53e0c0eb8dd4002cefc117fa588",
            "doctype": "json",
            "version": "2.1",
            "keyfrom": "fanyi.web",
            "action": "FY_BY_REALTlME",
        }
        # resp.json():直接把json格式的字符串转为python数据类型
        html = requests.post(url=self.post_url, data=data, headers=self.headers).json()
        # html = json.loads(html)
        result = html['translateResult'][0][0]["tgt"]

        print(result)

if __name__ == '__main__':
    spider = YdSpider()
    spider.attack_yd()




